#!/bin/sh
# filename: dlogon
# description: logon Mediaflux
# usage: dlogon name, where a list of name:host-name:port:username
#                     is stored in .daris file
# Toan Nguyen, June 2012, Monash Biomedical Imaging,Monash University

#     Copyright © 2012-2013 Toan Nguyen <toan.nguyen@monash.edu> 
#
#     This file is part of Xglom.
# 
#     This is free software: you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation, either version 3 of the License, or
#     (at your option) any later version.
# 
#     This is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
# 
#     You should have received a copy of the GNU General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.

# ========= MAIN SCRIPT ============
# check if arguments (command) are specified
if [[ $# -eq 0 ]]; then
	echo "Error: no argument is specified."
        echo "Usage: dlogon name"
	exit 1
fi

# check system
. dcheck

STR_NAME=$1

if [ ! -f ~/.daris ]; then
    echo "Error: file .daris does not exist!"
    exit 1
fi

# parse account information
SUCCESS=0
for strline in $(cat ~/.daris); do
    substrings=${strline//:/ }
    set -- $substrings
    if [ "$1" == ${STR_NAME} ]; then
        MFLUX_HOST=$2
        MFLUX_TRANSPORT=$3
        MFLUX_PORT=$4
        MFLUX_DOMAIN=$5
        MFLUX_USER=$6

        MFHOSTNAME=$1
        MFLUX_SID_FILE=~/.MFLUX_SID_$MFHOSTNAME;

        export MFLUX_HOST;
        export MFLUX_TRANSPORT;
        export MFLUX_PORT;
        export MFLUX_SID_FILE;

	    parameters_file_name=~/.daris_current_parameters
        if [ -f $parameters_file_name ]; then
            rm $parameters_file_name
        fi
        
	    echo "#!/bin/bash" >> $parameters_file_name
        echo MFLUX_HOST=$MFLUX_HOST >> $parameters_file_name
        echo MFLUX_TRANSPORT=$MFLUX_TRANSPORT >> $parameters_file_name
        echo MFLUX_PORT=$MFLUX_PORT >> $parameters_file_name
        echo MFLUX_SID_FILE=$MFLUX_SID_FILE >> $parameters_file_name

	    echo export MFLUX_HOST >> $parameters_file_name
	    echo export MFLUX_TRANSPORT >> $parameters_file_name
	    echo export MFLUX_PORT >> $parameters_file_name
	    echo export MFLUX_SID_FILE >> $parameters_file_name

        SUCCESS=1

        break
    fi
done

if [ $SUCCESS == 0 ]; then
    echo "Error: cannot find setting, check name again"
    exit 1
fi

echo "Input your password:\c"
stty -echo
read MFLUX_PASSWORD
stty echo
echo ""

$MFCOMMAND logon $MFLUX_DOMAIN $MFLUX_USER "$MFLUX_PASSWORD"
